<?php
/**
 * Created by PhpStorm.
 * Date: 2018/4/10
 * Time: 10:47
 */

namespace Et;

/**
 * Class Event
 *
 * @package Etong
 */
class Event {

    /**
     * 事件列表
     *
     * @var array
     */
    protected static $events = [];

    /**
     * 实例
     *
     * @var object
     */
    protected static $instance = '';

    public function __construct ($events = [])
    {
        self::$events = $events;
    }

    /**
     * 取得配置的单例
     *
     * @param array $config
     * @return Event
     */
    public static function getInstance ($config = [])
    {
        if (!self::$instance instanceof self) {
            self::$instance = new Event($config);
        }
        return self::$instance;

    }

    /**
     * 添加事件
     *
     * @param $event
     * @param $callback
     */
    public function add ($event, $callback)
    {
        self::$events[$event] = $callback;
    }

    public function get ($event)
    {
        if ($this->has($event)) {
            return self::$events[$event];
        }
        return null;
    }

    /**
     * 判断是否存在事件列表中
     *
     * @param $event
     * @return bool
     */
    public function has ($event)
    {
        if (isset(self::$events[$event])) {
            return true;
        }
        return false;
    }

    /**
     * 移除事件
     *
     * @param $event
     * @return bool
     */
    public function remove ($event)
    {

        if (isset(self::$events[$event])) {
            unset(self::$events[$event]);
        }
        return true;
    }

    /**
     * 获取所有的注册事件
     *
     * @return array
     */
    public function all ()
    {
        return self::$events;
    }

    /**
     * 触发事件
     *
     * @param $event
     */
    public function hook ($event)
    {
        if (!$this->has($event)) {
            return null;
        }

        $hook = self::$events[$event];
        if (is_callable($hook)) {
            $params = func_get_args();
            call_user_func_array($hook,$params);
            return null;
        }

        if (!class_exists($hook)) {
            return null;
        }
        $class = new $hook();
        //调用事件的run方法
        return $class->run();

    }
}